namespace Pentago.Core
{
    public class GameMaster : IGameMaster
    {
        private readonly IPlayerSelect0r playerSelect0r;
        private readonly IOut output;
        private readonly IIn input;
        private readonly IGameBoard board;

        Marble currentPlayer;

        public GameMaster(IPlayerSelect0r playerSelect0r, IOut output, IIn input, IGameBoard board)
        {
            this.playerSelect0r = playerSelect0r;
            this.output = output;
            this.input = input;
            this.board = board;
        }

        public void SetupNewGame()
        {
            currentPlayer = playerSelect0r.Select();

            output.Write(string.Format("{0} will start.", currentPlayer));
        }

        public void Start()
        {
            output.Write(string.Format("{0}, please enter new position: (block/location)", currentPlayer));
            var command = input.Read();
            
            while (command != "quit")
            {
                board.PlaceMarble(GetBlock(command), GetLocation(command), currentPlayer);

                output.Write(string.Format("{0}, please enter the block to twist with direction: (block/[cw|ccw])", currentPlayer));
                command = input.Read();
                
                board.TwistBlock(GetBlock(command), GetDirection(command));
                currentPlayer = EndTurn(currentPlayer);

                output.Write(string.Format("{0}, please enter new position: (block/location)", currentPlayer));
                command = input.Read();
            }

            output.Write("Stopping.");
        }

        private Marble EndTurn(Marble currentPlayer)
        {
            return currentPlayer == Marble.White ? Marble.Black : Marble.White;
        }

        private int GetBlock(string command)
        {
            return int.Parse(command.Split('/')[0]);
        }

        private int GetLocation(string command)
        {
            return int.Parse(command.Split('/')[1]);
        }

        private Direction GetDirection(string command)
        {
            return command.Split('/')[1] == "cw" ? Direction.Clockwise : Direction.CounterClockwise;
        }
    }
}